<template>
	<view class="marpadd" style="background: #F8F9FA;">
		<!-- <call-nav-bar :title="title">
		</call-nav-bar> -->
		<!-- @keyboardHeightChange="keyboardHeightChange" @hidedKeyboard="hidedKeyboard" -->
		<z-paging ref="paging" v-model="msgList" use-chat-record-mode safe-area-inset-bottom bottom-bg-color="#f8f8f8"
			@query="getChatHistory">

			<!-- for循环渲染聊天记录列表 -->
			<view v-for="(item,index) in msgList" :key="index" style="position: relative;">
				<!-- 如果要给聊天item添加长按的popup，请在popup标签上写style="transform: scaleY(-1);"，注意style="transform: scaleY(-1);"不要写在最外层，否则可能导致popup被其他聊天item盖住 -->
				<!-- <view class="popup" style="transform: scaleY(-1);">popUp</view> -->
				<view style="transform: scaleY(-1);padding: 0 24rpx;">

					<!-- -->
					<view class=" d-j-center " v-if="shouldDisplayTime(item.updatedAt,index)">
						<view class="box d-center white-font time-c" style="">
							{{item.updatedAt}}
						</view>
					</view>
					<view class="d-a-center mar-reply" :class="item.roleType==0?'d-j-end':''">
						<view class="" v-show="item.roleType==2||item.roleType==1">
							<image :src="userAvatar" class="qu-g yuan" mode=""></image>
						</view>
						<view v-if="item.messageType==0" class="box reply-box br-b text-a "
							:class="item.roleType==0?'white-bac co-f':'blue-bac co-white'">
							{{item.message}}
						</view>
						<view class="content box df mar br-a white-bac" v-if="item.messageType==1"
							style="width: 82%;padding:3%">
							<view class=" d-center" v-if="sessionTypeValue==2">
								<image :src="item.message.coverJson" class="qu-order-img br-a" mode="">
								</image>
							</view>
							<view class=" change-flex d-j-bet box" style="width: 100%;padding: 2% 3%;">
								<view class="d-j-bet user-order-top" style="">
									<view class="text-g omit co-f" style="width: 70%;">
										{{item.message.serviceName}}
									</view>
									<view class="text-a co-h">
										{{orderStatus(item.message.status)}}
									</view>
								</view>
								<view class="">
									<view class="change-flex d-j-bet wid-ten box hei-ten">
										<view class="text-a co-h" v-if="item.message.scheduleTime">
											{{item.message.scheduleTime.slice(0,-9)}}
										</view>
										<view class="d-j-bet d-a-center">
											<view class="text-g co-f">
												¥{{item.message.price}}
											</view>
											<view class="co-white d-center text-a blue-bac action-btn br-e"
												@click="serviceAction(item.message.number,item.message.status)">
												查看订单
											</view>
										</view>
									</view>
								</view>

							</view>
						</view>
						<view class="wid-ten" :class="item.messageType==2&&item.roleType==0?'d-j-end':''"
							v-if="item.messageType==2" style="padding-right: 20rpx;">
							<image class=" d-j-end" :src="item.message" mode="aspectFit"
								style="height: 200rpx;width: 200rpx" @click="previewImage(item.message,index)">
							</image>
						</view>
						<view class="" v-show="item.roleType==0">
							<image :src="kefuAvatar" class="qu-g yuan" mode=""></image>
						</view>
					</view>
				</view>
				<!-- style="transform: scaleY(-1)"必须写，否则会导致列表倒置 -->
				<!-- 注意不要直接在chat-item组件标签上设置style，因为在微信小程序中是无效的，请包一层view -->

			</view>
			<!-- 底部聊天输入框 -->
			<template #bottom>
				<view class="keyword-bc box mar d-a-center" :style="isOpenPic?'height: 336rpx;':'height: 150rpx;'">
					<view class="mar " style="width: 90%;">
						<view class="d-j-bet">
							<view class="" style="width: 90%;">
								<uni-easyinput v-model="message" @confirm="sendMessage(message,0)" :confirmHold="true"
									:inputBorder="inputBorder" placeholder="请输入内容..." @focus="handleStatus"
									:placeholderStyle="placeholderStyle" :autoHeight="autoHeight"
									style="height: 72rpx" />
							</view>
							<view class="d-center" v-if="message" @click="sendMessage(message,0)">
								发送
							</view>
							<view class="d-center" v-else @click="openPic()">
								<image class="qu-c"
									src="http://loto.oss-cn-shanghai.aliyuncs.com/email/b2bd099cb85a4f2e.png" mode="">
								</image>
							</view>
						</view>
						<view class="d-j-bet box mar" style="padding-top: 5%;width: 60%;" v-if="isOpenPic">
							<view class="" v-for="(item,index) in actionList" :key="index"
								@click="toSelectBottom(index)">
								<image class="qu-d" :src="item.icon" mode=""></image>
								<view class="d-j-center text-a co-k">
									{{item.name}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</template>
		</z-paging>





		<!-- <view class="mar" style="width: 100%;">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y box" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scrollView" :scroll-into-view="scrollToView"
				:style="isOpenPic?'min-height:87vh;':'min-height:77vh;'">
				<view class="box" style="padding: 3%;">
					<uni-load-more :status="isMore" :contentText='contentText'
						@clickLoadMore="pushMoreList"></uni-load-more>
					<view class="mar box change-order text-d co-f" style="margin-top: 3%;width: 30%;padding: 1%;">
						用户ID：{{chatId}}
					</view>
					<view class="" v-for="(item,index) in msgList" :key="index" :id="'msg' + index">
						<view class=" d-j-center " v-if="item.updatedAt">
							<view class="box d-center white-font time-c" style="">
								{{item.updatedAt}}
							</view>
						</view>
						<view class="d-a-center mar-reply" :class="item.roleType==0?'d-j-end':''">
							<view class="" v-show="item.roleType==2||item.roleType==1">
								<image :src="userAvatar" class="qu-g yuan" mode=""></image>
							</view>
							<view v-if="item.messageType==0" class="box reply-box br-b text-a "
								:class="item.roleType==0?'white-bac co-f':'blue-bac co-white'">
								{{item.message}}
							</view>
							<view class="content box df mar br-a white-bac" v-if="item.messageType==1"
								style="width: 82%;padding:3%">
								<view class=" d-center" v-if="sessionTypeValue==2">
									<image :src="item.message.coverJson" class="qu-order-img br-a" mode="">
									</image>
								</view>
								<view class=" change-flex d-j-bet box" style="width: 100%;padding: 2% 3%;">
									<view class="d-j-bet user-order-top" style="">
										<view class="text-g omit co-f" style="width: 70%;">
											{{item.message.serviceName}}
										</view>
										<view class="text-a co-h">
											{{orderStatus(item.message.status)}}
										</view>
									</view>
									<view class="">
										<view class="change-flex d-j-bet wid-ten box hei-ten">
											<view class="text-a co-h" v-if="item.message.scheduleTime">
												{{item.message.scheduleTime.slice(0,-9)}}
											</view>
											<view class="d-j-bet d-a-center">
												<view class="text-g co-f">
													¥{{item.message.price}}
												</view>
												<view class="co-white d-center text-a blue-bac action-btn br-e"
													@click="serviceAction(item.message.number,item.message.status)">
													查看订单
												</view>
											</view>
										</view>
									</view>

								</view>
							</view>
							<view class="wid-ten" :class="item.messageType==2&&item.roleType==0?'d-j-end':''"
								v-if="item.messageType==2" style="padding-right: 20rpx;">
								<image class=" d-j-end" :src="item.message" mode="aspectFit"
									style="height: 200rpx;width: 200rpx" @click="previewImage(item.message,index)">
								</image>
							</view>
							<view class="" v-show="item.roleType==0">
								<image :src="kefuAvatar" class="qu-g yuan" mode=""></image>
							</view>
						</view>
					</view>
					<view class="" :class="isOpenPic?'sty1':'sty2'" id="openView">
					</view>
				</view>
			</scroll-view>

		</view> -->
		<!-- 键盘 -->
		<!-- <view class="keyword-bc box mar d-a-center" style="" :style="isOpenPic?'height: 336rpx;':'height: 150rpx;'">
			<view class="mar " style="width: 90%;">
				<view class="d-j-bet">
					<view class="" style="width: 90%;">
						<uni-easyinput v-model="message" :inputBorder="inputBorder" placeholder="请输入内容..."
							@focus="handleStatus" :placeholderStyle="placeholderStyle" :autoHeight="autoHeight"
							style="height: 72rpx" />
					</view>
					<view class="d-center" v-if="message" @click="sendMessage(message,0)">
						发送
					</view>
					<view class="d-center" v-else @click="openPic()">
						<image class="qu-c" src="http://loto.oss-cn-shanghai.aliyuncs.com/email/b2bd099cb85a4f2e.png"
							mode="">
						</image>
					</view>
				</view>
				<view class="d-j-bet box mar" style="padding-top: 5%;width: 60%;" v-if="isOpenPic">
					<view class="" v-for="(item,index) in actionList" :key="index" @click="toSelectBottom(index)">
						<image class="qu-d" :src="item.icon" mode=""></image>
						<view class="d-j-center text-a co-k">
							{{item.name}}
						</view>
					</view>
				</view>
			</view>
		</view> -->
	</view>

</template>

<script>
	import {
		userUrl
	} from '@/utils/options.js'
	import uniPopup from '@/components/uni-ui/uni-popup/uni-popup.vue'
	import {
		debounce
	} from '@/common/js/common.js';
	import userOrder from '@/components/common/user-chat/user-order.vue'
	import callNavBar from '@/components/common/user-chat/call-nav-bar.vue'
	import {
		getChatHistory,
		sendMessageKefu,
		markMessagesAsRead
	} from '@/apis/chat/index.js'
	import socket from '@/common/js/socket.js'
	export default {
		components: {
			callNavBar,
			userOrder,
			uniPopup
		},
		data() {
			return {
				isMore: 'more',
				contentText: {
					contentdown: "点击加载更多",
					contentrefresh: "正在加载中...",
					contentnomore: "没有更多数据了"
				},
				orderNum: 0,
				scrollToView: '',
				isOpenPic: false,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				autoHeight: true,
				inputBorder: true,
				content: '',
				placeholderStyle: 'fontSize:28rpx;color: #BAC1CE;fontWeight: 400;',
				actionList: [{
					icon: 'http://loto.oss-cn-shanghai.aliyuncs.com/email/951fa1acfc804f6f.png',
					name: '相册',
				}, {
					icon: 'http://loto.oss-cn-shanghai.aliyuncs.com/email/873f730a228f4e97.png',
					name: '拍摄',
				}, ],
				questionList: [],
				// 聊天记录的唯一标识
				chatId: '',
				message: '',
				// 判断是用户还是客服发的消息,0是客服，1是用户,2是护士
				socketTask: null,
				// 默认关闭
				isClose: true,
				// 等待时间
				timer: 10000,
				page: {
					page: 1,
					pageSize: 5
				},
				hisPage: {
					page: 1,
					pageSize: 10
				},
				msgList: [],
				userAvatar: '',
				kefuAvatar: 'http://loto.oss-cn-shanghai.aliyuncs.com/email/b8ad69f2e0854d21.png',
				order: {},
				historyList: [],
				lastId: 0,
				receiverId: '',
				proLen: 0,
				filterStatus: 0,
				title: '',
				preImage: '',
				sessionTypeValue: '',
				numId: '',
				map: {
					18888888888: '80',
					16666666666: '81'
				},
				map1: {
					18888888888: '/2',
					16666666666: '/1'
				},
				userInfo: null,
				seriveId: 0,
			};
		},
		mounted() {},
		computed: {

		},
		// onReachBottom() {
		// 	uni.$emit('onReachBottom') // 设置监听事件
		// },
		onLoad(option) {
			this.userInfo = uni.getStorageSync('userInfo')
			this.receiverId = this.map[this.userInfo.mobile]
			this.seriveId = this.map[this.userInfo.mobile]
			this.lastId = 0
			console.log('路由-------', option);
			this.sessionTypeValue = option.sessionType
			if (option.sessionType == 1) {
				option.sessionType = '护士'
			} else if (option.sessionType == 2) {
				option.sessionType = '用户'
			}
			this.numId = option.id
			this.chatId = option.userId
			this.title = option.sessionType + option.userNickname
			this.init()
			uni.setNavigationBarTitle({
				title: this.title
			})
		},
		onShow() {
			this.toBottomView()
		},
		onReady() {},
		destroyed() {
			this.socketTask.close();
			this.knowMsg()
		},
		methods: {

			shouldDisplayTime(prevTimeStr, index) {
				if (this.msgList.length < 2 || index < 1 || this.msgList.length - index <= 1) return prevTimeStr ? true :
					false

				// 将时间字符串转换为Date对象  
				const prevTime = new Date(prevTimeStr);
				const currentTime = new Date(this.msgList[index + 1].updatedAt);

				// 计算时间差（毫秒）  
				const diff = currentTime - prevTime;
				return diff <= -60000;

			},
			serviceAction(number, status) {
				console.log('lllll');
				uni.navigateTo({
					url: '/pages/order/order-detaile/order-detaile?number=' + number + '&status=' + status +
						'&callIndex=' + 1
				})
			},
			async knowMsg() {
				let res = await markMessagesAsRead(this.numId, this.chatId)
				if (res.success) {
					console.log('消息已读成功');
				}
			},
			orderStatus(status) {
				let title = '';
				switch (status) {
					case 1:
						title = '待付款';
						break;
					case 2:
						title = '待接单';
						break;
					case 3:
						title = '进行中';
						break;
					case 4:
						title = '进行中'; //服务中
						break;
					case 5:
						title = '已完成';
						break;
					case 6:
						title = '已取消';
						break;
					case 7:
						title = '已退款';
						break;
					case 9:
						title = '进行中'; //待审核
						break;
					case 10:
						title = '进行中'; //已拒绝
						break;
				}
				return title;
			},
			previewImage(image, index) {
				this.preImage = ''
				this.preImage = image
				console.log('preImage', index, image);
				uni.previewImage({
					current: index,
					urls: [image],
					success: function(res) {},
					fail: function(res) {},
					complete: function(res) {
						console.log(res)
					},
				})
			},
			handleStatus() {
				console.log('键盘已经打开');
				// ios
				console.log(uni.getSystemInfoSync().platform);
				if (uni.getSystemInfoSync().platform === 'ios') {
					this.isOpenPic = false
				}
			},
			openPic() {
				this.isOpenPic = !this.isOpenPic
				this.$nextTick(function() {
					this.scrollToView = 'openView';
				})
				this.scrollToView = 'msg' + (this.msgList.length - 1);
			},
			connectSocket() {
				console.log("消息", this.chatId, this.seriveId);
				let that = this
				let port = that.map1[that.userInfo.mobile]
				that.socketTask = socket.connectSocket(that.seriveId + port)
				that.socketTask.onOpen(function(res) {
					console.log('websocket连接已打开！！！');
					that.getChatHistory()
					that.heart()
				})
				let msg = null
				that.socketTask.onMessage(function(res) {
					console.log('收到消息=========');
					msg = JSON.parse(res.data)
					if (msg) {
						let msgInfo = JSON.parse(msg.message)
						msgInfo.userAvatar = msg.avatarJson
						console.log(that.chatId, msg.senderId);
						if (that.chatId == msg.senderId) {
							if (msgInfo.messageType == 1) {
								msgInfo.message = JSON.parse(msgInfo.message)
								console.log(msgInfo.message);
							}
							that.$refs.paging.addChatRecordData(msgInfo)
							that.toBottomView()
						}
					}
				})
				that.socketTask.onError(function(res) {
					console.log('websocket连接打开失败，请检查---', res);
					// 进入重新连接
					that.reconnect()
				})
				that.socketTask.onClose((e) => {
					console.log('websocket连接关闭');
					clearInterval(that.timer)
					that.timer = ''
					if (!that.isClose) {
						that.reconnect()
					}
				})
			},
			async init() {
				let that = this
				that.connectSocket()
			},
			async getChatHistory() {
				if (this.msgList.length > 0) {
					this.lastId = this.msgList[this.msgList.length - 1].id
				} else {
					this.lastId = 0
				}
				console.log("ID", this.lastId)
				let res = await getChatHistory(this.lastId, this.hisPage.pageSize, this.receiverId, this.chatId)
				if (res.object.success) {
					if (res.object.object.length != 0) {
						this.userAvatar = res.object.object[0].userAvatar
						// console.log("数据",res.object.object)
						res.object.object.forEach((i, index) => {
							if (i.messageType == 1) {
								i.message = JSON.parse(i.message)
							}
						})
						this.$refs.paging.complete(res.object.object.reverse());
						console.log("数据", this.msgList)
						this.proLen = res.object.object.length
						// if (this.msgList.length > 0) {
						// 	this.msgList.splice(0, 0, ...res.object.object)
						// } else {
						// 	this.msgList = res.object.object
						// }

						this.$nextTick(function() {
							this.scrollToView = 'msg' + (this.proLen - 1);
						})
					}
					// console.log('多少------', this.msgList);
					if (this.lastId == 0) {
						console.log('新用户进入页面的时候');
						this.$nextTick(function() {
							this.scrollToView = 'msg' + (this.msgList.length - 1);
						})
					}
				}
			},
			// 进入重新连接
			reconnect() {
				console.log('进入断线重新连接');
				this.socketTask = null
				this.connectSocket()
			},
			// 发送消息
			async sendMessage(msg, type) {
				let that = this
				let info = {
					message: msg,
					messageType: type,
					receiverId: that.chatId,
					roleType: 0,
					senderId: this.seriveId,
					sessionType: that.sessionTypeValue,
				}
				let res = await sendMessageKefu(info)
				if (res.success) {
					console.log('发送成功----');
					this.$refs.paging.addChatRecordData(info)
					that.message = ''
					that.toBottomView()
				} else {
					uni.showToast({
						title: '请检查网络是否连接！',
						icon: 'none'
					});
				}
			},
			heart() {
				let that = this
				clearInterval(this.timer)
				this.timer = ''
				let msg = {
					"type": "heartbeat"
				}
				this.timer = setInterval(() => {
					that.sendSocketMessage(JSON.stringify(msg)).then(res => {
						console.log('心跳成功');
					}).catch(res => {
						console.log('发送失败', res);
					})
				}, 222000000)
			},
			toSelectBottom(index) {
				let that = this

				let sourceType = []
				if (index == 0) {
					sourceType = ['album']
				} else if (index == 1) {
					sourceType = ['camera']
				}
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: sourceType, //从相册选择
					success: function(res) {
						// console.log(JSON.stringify(res.tempFilePaths))					
						let tempFiles = res.tempFilePaths;
						let baseUrl = ''
						if (process.env.NODE_ENV === 'development') {
							// #ifndef H5
							baseUrl = userUrl
							// #endif
							// #ifdef H5
							baseUrl = '/api'
							// #endif
						} else if (process.env.NODE_ENV === 'production') {
							// 生产环境:正式地址
							baseUrl = userUrl
						}
						let url = baseUrl + '/user/otherOssController/ossUpload'
						// #ifndef MP-WEIXIN
						uni.uploadFile({
							url: url,
							filePath: tempFiles[0],
							name: 'file', // 在FormData 中文件对应的属性名
							fileType: 'image',
							header: {
								token: that.$store.state.token
							},
							success: r => {
								console.log(JSON.parse(r.data));
								let info = JSON.parse(r.data).object
								that.sendMessage(info, 2)
							},
							fail: err => {},
							complete: complete => {}
						})
						return
						// #endif
					},
					complete: function(res) {
						that.toBottomView()
					}
				});
			},
			toBottomView() {
				this.$nextTick(function() {
					this.scrollToView = 'msg' + (this.msgList.length - 1);
				})
			},
			// 点击发送状态是否成功
			sendClickStatus(val) {
				// console.log('点击发送状态是否成功', val);
				if (val) {
					this.sendMessage(val, 1, this.socketTask, 1)
					// this.order = JSON.parse(val)
					this.$refs.selectServiceOrder.close()
				}

			},
			pushMoreList(e) {
				console.log('ooo', e);
				let that = this
				let len = this.msgList.length
				that.isMore = 'loading'
				console.log('111', that.proLen);
				setTimeout(() => {
					if (len >= 10 && that.proLen == 10) {
						this.lastId = this.msgList[0].id
						this.getChatHistory()
						that.isMore = 'more'
					} else {
						this.lastId = 0
						that.isMore = 'noMore'
					}
				}, 1000)
			},
			upper: function(e) {
				let len = this.msgList.length
				setTimeout(() => {
					console.log('len', len, 'this.proLen', this.proLen);
					if (len >= 10 && this.proLen == 10) {
						this.lastId = this.msgList[0].id
						this.getChatHistory()
						this.isMore = 'more'
					} else {
						this.lastId = 0
						this.isMore = 'noMore'
					}
				}, 1000)
				this.pushMoreList()
			},
			lower: function(e) {
				console.log('拉到底部-----', e)
				this.orderNum++
				console.log(2222222222, this.orderNum);
			},
			scroll: function(e) {
				// console.log(333, e)
				this.old.scrollTop = e.detail.scrollTop
			},
			scrollView(e) {
				// console.log('每一次滑动变换位置-----', e);
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				uni.showToast({
					icon: "none",
					title: "纵向滚动 scrollTop 值已被修改为 0"
				})
			},
			toChangeOrder(value) {
				this.orderNum = 0
				this.filterStatus = value
				if (this.filterStatus == 9) {
					this.isOpenPic = true
				}
				this.$refs.selectServiceOrder.open()
			},
			toActionName(index) {
				if (index == 0) {
					// 服务进度
					uni.switchTab({
						url: '/pages/tabbars/order/order'
					})
				} else if (index == 1) {
					// 服务流程
					uni.navigateTo({
						url: '/pages/customerService/order-process'
					})
				} else if (index == 2) {
					// uni.navigateTo({
					// 	url: '/pagesB/pages/bill/index'
					// })
					uni.showToast({
						icon: 'none',
						title: '新功能，敬请期待～'
					})
				}
			},

		}
	};
</script>

<style scoped lang="less">
	.sty1 {
		height: 190rpx;
	}

	.sty2 {
		height: 40rpx;
	}

	.content {
		height: 220rpx;
	}

	.scroll-Y {
		height: 90vh;
	}

	.scroll-view_H {
		white-space: nowrap;
		width: 100%;
	}

	.scroll-view-item {
		height: 600rpx;
		line-height: 600rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.scroll-view-item_H {
		display: inline-block;
		width: 100%;
		height: 600rpx;
		line-height: 600rpx;
		text-align: center;
		font-size: 36rpx;
	}

	.tl {
		font-size: 28rpx;
		color: #333333;
	}

	.time-c {
		height: 40rpx;
		background: rgba(0, 0, 0, 0.1);
		border-radius: 6rpx;
		font-size: 20rpx;
		font-weight: 400;
		width: 232rpx;
		margin: 10rpx 0 10rpx 0;
	}

	.tll {
		font-size: 28rpx;
		color: #666666;
	}

	.menu-l {
		width: 98%;
		height: 194rpx;
	}

	.icon-img {
		font-size: 24rpx;
		color: rgba(0, 0, 0, 0.87);
	}

	.menu-ll {
		width: 98%;
		// height: 670rpx;
	}

	.menu-t {
		font-size: 32rpx;
		color: #3E3E3E;
	}

	.menu-tl {
		border-bottom: 1rpx solid beige;
	}

	.menu-c {
		font-size: 24rpx;
		color: #438AFF;
	}

	.order-s {
		width: 98%;
		height: 220rpx;
	}

	.chat-bc {
		background-image: url('http://loto.oss-cn-shanghai.aliyuncs.com/email/338c33478a854a02.png');
		background-size: 100%;
		background-repeat: no-repeat;
	}

	.keyword-bc {
		// position: fixed;
		// bottom: 0;
		// left: 0;
		// width: 100%;

		background: #F6F6F6;
	}
</style>